import Mock from 'mockjs';

// 创建内存数据库
const mockDatabase = (() => {
  // 生成案件数据
  const generateCases = () => {
    return Mock.mock({
      'list|50-100': [
        {
          'id|+1': 1000,
          'title': '@ctitle(10, 20)',
          'type': '@pick(["CIVIL", "CRIMINAL", "ADMINISTRATIVE", "OTHER"])', // 案件类型
          'apply_time': '@datetime', // 申请时间
          'description': '@cparagraph(2, 4)',
          'category': '@pick(["民事纠纷", "刑事辩护", "劳动纠纷", "婚姻家事", "合同纠纷", "知识产权", "其他"])',
          'priority|0-2': 0, // 0-低, 1-中, 2-高
          'status|0-4': 0, // 0-待受理, 1-处理中, 2-已完成, 3-已拒绝, 4-已取消
          'applicantId|1-50': 1,
          'applicantName': '@cname',
          'applicantPhone': /1[3-9]\d{9}/,
          'lawyerId|1-20': 1,
          'lawyerName': '@cname',
          'lawyerPhone': /1[3-9]\d{9}/,
          'location': '@county(true)',
          'budget|1000-50000': 5000,
          'createdAt': '@datetime',
          'updatedAt': '@datetime',
          'expectedCompletionDate': '@date("yyyy-MM-dd")',
          'actualCompletionDate': null,
          'documents|0-5': [
            {
              'id|+1': 1,
              'name': '@ctitle(5, 15)',
              'type': '@pick(["身份证", "合同", "证据材料", "其他"])',
              'url': '@url',
              'size|100-5000': 500,
              'uploadedAt': '@datetime'
            }
          ],
          'progress|0-100': 0,
          'notes': '@cparagraph(1, 3)',
          'tags|0-3': ['@pick(["紧急", "复杂", "新客户", "老客户"])'],
          'rating|1-5': 5,
          'review': '@cparagraph(1, 2)'
        }
      ]
    }).list;
  };

  return {
    generateCases
  };
})();

export { mockDatabase }

export const mockCases = [
  {
    id: 1,
    case_no: 'A20240001',
    user_id: 101,
    lawyer_id: 201,
    title: '合同纠纷',
    type: 'CIVIL', // 枚举: CIVIL, CRIMINAL, ADMINISTRATIVE, OTHER
    description: '因合同履行发生争议，申请法律援助。',
    status: 'PENDING', // 枚举: PENDING, REVIEWING, ASSIGNED, IN_PROGRESS, COMPLETED, CLOSED
    apply_time: '2024-05-01 10:00:00',
    assign_time: null,
    accept_time: null,
    complete_time: null,
    close_reason: null
  },
  {
    id: 2,
    case_no: 'A20240002',
    user_id: 102,
    lawyer_id: 202,
    title: '交通事故',
    type: 'CIVIL',
    description: '交通事故责任认定有争议。',
    status: 'IN_PROGRESS',
    apply_time: '2024-05-02 09:30:00',
    assign_time: '2024-05-02 10:00:00',
    accept_time: '2024-05-02 10:30:00',
    complete_time: null,
    close_reason: null
  },
  {
    id: 3,
    case_no: 'A20240003',
    user_id: 103,
    lawyer_id: null,
    title: '行政处罚申诉',
    type: 'ADMINISTRATIVE',
    description: '对行政处罚决定不服，申请复议。',
    status: 'REVIEWING',
    apply_time: '2024-05-03 14:20:00',
    assign_time: null,
    accept_time: null,
    complete_time: null,
    close_reason: null
  },
  {
    id: 4,
    case_no: 'A20240004',
    user_id: 104,
    lawyer_id: 204,
    title: '刑事辩护',
    type: 'CRIMINAL',
    description: '涉嫌刑事犯罪，申请法律援助。',
    status: 'ASSIGNED',
    apply_time: '2024-05-04 11:00:00',
    assign_time: '2024-05-04 12:00:00',
    accept_time: null,
    complete_time: null,
    close_reason: null
  },
  {
    id: 5,
    case_no: 'A20240005',
    user_id: 105,
    lawyer_id: 205,
    title: '其他类型案件',
    type: 'OTHER',
    description: '其他类型法律援助申请。',
    status: 'CLOSED',
    apply_time: '2024-05-05 08:00:00',
    assign_time: '2024-05-05 09:00:00',
    accept_time: '2024-05-05 09:30:00',
    complete_time: '2024-05-06 10:00:00',
    close_reason: '申请人撤回' 
  }
]

/**
 * 案件模块Mock配置
 * @param {MockAdapter} mock - Mock适配器实例
 */
export default function(mock) {
  // 获取案件列表（带分页和筛选）
  mock.onGet('/cases').reply(config => {
    const { 
      page = 1, 
      size = 10, 
      status, 
      category, 
      priority, 
      keyword,
      lawyerId,
      applicantId
    } = config.params;
    
    let filteredCases = [...mockDatabase.generateCases()];
    
    // 状态筛选
    if (status !== undefined) {
      filteredCases = filteredCases.filter(c => c.status === parseInt(status));
    }
    
    // 类别筛选
    if (category) {
      filteredCases = filteredCases.filter(c => c.category === category);
    }
    
    // 优先级筛选
    if (priority !== undefined) {
      filteredCases = filteredCases.filter(c => c.priority === parseInt(priority));
    }
    
    // 律师筛选
    if (lawyerId) {
      filteredCases = filteredCases.filter(c => c.lawyerId === parseInt(lawyerId));
    }
    
    // 申请人筛选
    if (applicantId) {
      filteredCases = filteredCases.filter(c => c.applicantId === parseInt(applicantId));
    }
    
    // 关键词搜索
    if (keyword) {
      filteredCases = filteredCases.filter(c => 
        c.title.includes(keyword) || 
        c.description.includes(keyword) ||
        c.applicantName.includes(keyword) ||
        c.lawyerName.includes(keyword)
      );
    }
    
    // 按创建时间倒序排列
    filteredCases.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
    
    const start = (page - 1) * size;
    const end = start + size;
    const paginated = filteredCases.slice(start, end);
    
    return [200, {
      code: 200,
      data: paginated,
      pagination: {
        page: parseInt(page),
        size: parseInt(size),
        total: filteredCases.length,
        totalPages: Math.ceil(filteredCases.length / size)
      }
    }];
  });

  // 获取单个案件详情
  mock.onGet(/\/cases\/\d+$/).reply(config => {
    const caseId = config.url.split('/').pop();
    const caseItem = mockDatabase.generateCases().find(c => c.id == caseId);
    
    return caseItem 
      ? [200, { code: 200, data: caseItem }]
      : [404, { code: 404, message: '案件不存在' }];
  });

  // 创建案件
  mock.onPost('/cases').reply(config => {
    const newCase = JSON.parse(config.data);
    newCase.id = Math.max(...mockDatabase.generateCases().map(c => c.id)) + 1;
    newCase.createdAt = new Date().toISOString();
    newCase.updatedAt = new Date().toISOString();
    newCase.status = 0; // 默认待受理
    newCase.progress = 0;
    newCase.documents = [];
    newCase.tags = [];
    newCase.rating = null;
    newCase.review = null;
    
    mockDatabase.generateCases().unshift(newCase);
    
    return [201, { 
      code: 201, 
      message: '案件创建成功',
      data: newCase
    }];
  });

  // 更新案件
  mock.onPut(/\/cases\/\d+$/).reply(config => {
    const caseId = config.url.split('/').pop();
    const updateData = JSON.parse(config.data);
    
    const caseIndex = mockDatabase.generateCases().findIndex(c => c.id == caseId);
    
    if (caseIndex === -1) {
      return [404, { code: 404, message: '案件不存在' }];
    }
    
    // 更新案件信息
    mockDatabase.generateCases()[caseIndex] = {
      ...mockDatabase.generateCases()[caseIndex],
      ...updateData,
      id: parseInt(caseId), // 确保ID不被修改
      updatedAt: new Date().toISOString()
    };
    
    return [200, { 
      code: 200, 
      message: '案件信息更新成功',
      data: mockDatabase.generateCases()[caseIndex]
    }];
  });

  // 删除案件
  mock.onDelete(/\/cases\/\d+$/).reply(config => {
    const caseId = config.url.split('/').pop();
    const caseIndex = mockDatabase.generateCases().findIndex(c => c.id == caseId);
    
    if (caseIndex === -1) {
      return [404, { code: 404, message: '案件不存在' }];
    }
    
    mockDatabase.generateCases().splice(caseIndex, 1);
    
    return [200, { 
      code: 200, 
      message: '案件删除成功' 
    }];
  });

  // 更新案件状态
  mock.onPatch(/\/cases\/\d+\/status/).reply(config => {
    const caseId = config.url.split('/').pop();
    const { status, notes } = JSON.parse(config.data);
    
    const caseItem = mockDatabase.generateCases().find(c => c.id == caseId);
    
    if (!caseItem) {
      return [404, { code: 404, message: '案件不存在' }];
    }
    
    caseItem.status = status;
    caseItem.updatedAt = new Date().toISOString();
    
    // 根据状态更新进度
    if (status === 1) { // 处理中
      caseItem.progress = 50;
    } else if (status === 2) { // 已完成
      caseItem.progress = 100;
      caseItem.actualCompletionDate = new Date().toISOString();
    }
    
    if (notes) {
      caseItem.notes = notes;
    }
    
    return [200, { 
      code: 200, 
      message: '案件状态更新成功',
      data: caseItem
    }];
  });

  // 更新案件进度
  mock.onPatch(/\/cases\/\d+\/progress/).reply(config => {
    const caseId = config.url.split('/').pop();
    const { progress } = JSON.parse(config.data);
    
    const caseItem = mockDatabase.generateCases().find(c => c.id == caseId);
    
    if (!caseItem) {
      return [404, { code: 404, message: '案件不存在' }];
    }
    
    caseItem.progress = Math.min(100, Math.max(0, progress));
    caseItem.updatedAt = new Date().toISOString();
    
    return [200, { 
      code: 200, 
      message: '案件进度更新成功',
      data: caseItem
    }];
  });

  // 分配律师
  mock.onPost(/\/cases\/\d+\/assign/).reply(config => {
    const caseId = config.url.split('/').pop();
    const { lawyerId, lawyerName } = JSON.parse(config.data);
    
    const caseItem = mockDatabase.generateCases().find(c => c.id == caseId);
    
    if (!caseItem) {
      return [404, { code: 404, message: '案件不存在' }];
    }
    
    caseItem.lawyerId = lawyerId;
    caseItem.lawyerName = lawyerName;
    caseItem.updatedAt = new Date().toISOString();
    
    return [200, { 
      code: 200, 
      message: '律师分配成功',
      data: caseItem
    }];
  });

  // 案件评价
  mock.onPost(/\/cases\/\d+\/review/).reply(config => {
    const caseId = config.url.split('/').pop();
    const { rating, review } = JSON.parse(config.data);
    
    const caseItem = mockDatabase.generateCases().find(c => c.id == caseId);
    
    if (!caseItem) {
      return [404, { code: 404, message: '案件不存在' }];
    }
    
    caseItem.rating = rating;
    caseItem.review = review;
    caseItem.updatedAt = new Date().toISOString();
    
    return [200, { 
      code: 200, 
      message: '评价提交成功',
      data: caseItem
    }];
  });

  // 获取案件统计信息
  mock.onGet('/cases/stats').reply(() => {
    const totalCases = mockDatabase.generateCases().length;
    const pendingCases = mockDatabase.generateCases().filter(c => c.status === 0).length;
    const processingCases = mockDatabase.generateCases().filter(c => c.status === 1).length;
    const completedCases = mockDatabase.generateCases().filter(c => c.status === 2).length;
    const rejectedCases = mockDatabase.generateCases().filter(c => c.status === 3).length;
    
    const categoryStats = {};
    const priorityStats = { low: 0, medium: 0, high: 0 };
    
    mockDatabase.generateCases().forEach(c => {
      categoryStats[c.category] = (categoryStats[c.category] || 0) + 1;
      if (c.priority === 0) priorityStats.low++;
      else if (c.priority === 1) priorityStats.medium++;
      else priorityStats.high++;
    });
    
    const avgRating = mockDatabase.generateCases()
      .filter(c => c.rating)
      .reduce((sum, c) => sum + c.rating, 0) / 
      mockDatabase.generateCases().filter(c => c.rating).length || 0;
    
    return [200, {
      code: 200,
      data: {
        total: totalCases,
        pending: pendingCases,
        processing: processingCases,
        completed: completedCases,
        rejected: rejectedCases,
        categoryStats,
        priorityStats,
        avgRating: Math.round(avgRating * 10) / 10,
        recentCases: mockDatabase.generateCases()
          .sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
          .slice(0, 5)
      }
    }];
  });

  // 上传案件文档
  mock.onPost(/\/cases\/\d+\/documents/).reply(config => {
    const caseId = config.url.split('/').pop();
    
    // 模拟文件上传
    const document = {
      id: Date.now(),
      name: Mock.Random.ctitle(5, 15),
      type: Mock.Random.pick(['身份证', '合同', '证据材料', '其他']),
      url: Mock.Random.url(),
      size: Mock.Random.integer(100, 5000),
      uploadedAt: new Date().toISOString()
    };
    
    const caseItem = mockDatabase.generateCases().find(c => c.id == caseId);
    if (caseItem) {
      caseItem.documents.push(document);
    }
    
    return [200, {
      code: 200,
      message: '文档上传成功',
      data: document
    }];
  });
} 